package com.kitty.http.game;


import com.kitty.common.utils.SpringUtils;
import com.kitty.common.start.GameServer;
import com.kitty.common.start.MyApplicationRunner;
import com.kitty.common.thread.IdGenerator;
import com.kitty.common.core.SchedulerManager;
import com.kitty.game.ServerService;
import com.kitty.game.admin.service.AdminService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.PetStore;
import com.kitty.game.equip.model.EquipBox;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.fight.service.OneThreadService;
import com.kitty.game.guard.model.Guard;
import com.kitty.game.guard.model.GuardBox;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBook;
import com.kitty.game.pet.model.PetBox;
import com.kitty.game.pet.service.BookService;
import com.kitty.game.player.PlayerService;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.AccountService;
import com.kitty.game.role.service.PayService;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.shidao.KuafuShidaoService;
import com.kitty.game.skill.model.RoleSkill;
import com.kitty.game.skill.model.SkillBox;
import com.kitty.game.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
//后加
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/scl/my")
@Slf4j
public class ServerControllerKF {

    @Autowired
    MyApplicationRunner myApplicationRunner;
    @Autowired(required = false)
    HttpServletResponse response;
    @Autowired
    private AdminService adminService;
    @Autowired
    AccountService accountService;
    @Autowired
    GameServer gameServer;
    @Autowired
    PlayerService playerService;
    @Autowired
    PayService payService;
    @Autowired
    RoleService roleService;
    @Autowired
    ChatService chatService;
    @Autowired
    KuafuShidaoService kuafuShidaoService;
    @Autowired
    Dao dao;

    @RequestMapping(method = RequestMethod.GET, path = "id")
    @ResponseBody
    public Object id() {
        NutMap nutMap = new NutMap();
        nutMap.setv("roleId",roleService.getRoleId());
        nutMap.setv("uid", IdGenerator.getNextId());
        return nutMap;
    }

    @RequestMapping(path = "startKuafu")
    @ResponseBody
    public void startKuafu(String content) {
        //23##00
        log.error("跨服试道通知=={}",content);
        String[]strings = content.split("##");
        Date curr = new Date();
        String starttime = TimeUtil.formatDate(curr,"yyyy-MM-dd")+ " "+strings[0]+":"+strings[1]+":00";
        Date date = TimeUtil.parse(starttime,"yyyy-MM-dd HH:mm:ss");
        long delay = (date.getTime()-curr.getTime())/1000;
        if (delay <= 0){
            delay = 1;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,30);
        int  h= calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        SpringUtils.getBean(ServerService.class).getScheduledExecutorService().schedule(new Runnable() {
            @Override
            public void run() {
                SpringUtils.getBean(KuafuShidaoService.class).content = (System.currentTimeMillis()+30*TimeUtil.ONE_MINUTE)+"";
            }
        },delay, TimeUnit.SECONDS);

        String notice = "本次跨服试道大会将于#R"+strings[0]+":"+strings[1]+"开始报名，"+h+":"+m+"结束报名，报名完成后请及时前往跨服专区，以免错过时间#n，恭候各位道友准时降临跨服试道专线（组队报名只会传输队长信息！请所有人单独报名！单人找#R跨服赛事接引人申请报名#n，然后小退进入#R选区界面#n，进入#R跨服专线#n，进入跨服以后再进行组队报名进跨服试道场）！#51 #82";
        SchedulerManager.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                chatService.sendAdnotice(notice);
            }
        }, 1000);
        for (int i = 0; i < 11; i++) {
            SchedulerManager.getInstance().schedule(new Runnable() {
                @Override
                public void run() {
                    chatService.sendAdnotice(notice);
                }
            }, 60000 * (i + 1));
        }
    }

    @RequestMapping(path = "kuafuReward")
    @ResponseBody
    public void kuafuReward(String content) {
        kuafuShidaoService.sendReward(content);
    }

    @RequestMapping(path = "enterReward")
    @ResponseBody
    public void enterReward(String content) {
        kuafuShidaoService.enterReward(content);
    }


//    @RequestMapping(method = RequestMethod.GET, path = "flash")
//    @ResponseBody
//    public Object flash() {
//        SpringUtils.getBean(PlayerService.class).loadAllPlayerProfiles();
//        return "更新成功";
//    }

    @RequestMapping(method = RequestMethod.GET, path = "login")
    @ResponseBody
    public Object login(@RequestParam("kuafuUid") long kuafuUid,@RequestParam("ip") String ip,@RequestParam("port") int port,@RequestParam("gmport") int gmport,@RequestParam("sid") String sid,@RequestParam("uid") String uid) {
        NutMap nutMap = NutMap.NEW();
        nutMap.setv("kuafuUid",kuafuUid);
        nutMap.setv("ip",ip);
        nutMap.setv("port",port);
        nutMap.setv("gmport",gmport);
        nutMap.setv("uid",uid);
        Role role = SpringUtils.getPlayerService().getPlayerBy(kuafuUid);
        if (role != null ){
            insert(role);
            log.error("插入数据成功============={}",kuafuUid,role.getName());
        }
        SpringUtils.getBean(OneThreadService.class).addFightTask(0, new Runnable() {
            @Override
            public void run() {
                SpringUtils.getBean(PlayerService.class).loadAllPlayerProfiles();
            }
        });
        log.error("插入数据成功=={}",Json.toJson(nutMap));
        return "成功";
    }

    private void insert(Role role){
        HashMap<Integer, Integer> oldequipId_newequipId = new HashMap<>();
        {
            EquipBox equipBox = role.getEquipBox();
            Map<Integer, RoleEquip> equips = new ConcurrentHashMap<>(equipBox.getEquips());
            equipBox.getEquips().clear();
            for (Map.Entry<Integer, RoleEquip> entry : equips.entrySet()) {
                int oldequipId = entry.getValue().getId();
                entry.getValue().setId(SpringUtils.getIdentityService().getNextId(IdentityType.ROLE_EQUIP));
                entry.getValue().setRoleId(role.getRoleId());
                equipBox.getEquips().put(entry.getValue().getId(), entry.getValue());
                oldequipId_newequipId.put(oldequipId, entry.getValue().getId());
            }
        }
        // 守护
        {
            GuardBox guardBox = role.getGuardBox();
            for (Guard guard : guardBox.getGuards()) {
                guard.setId(SpringUtils.getIdentityService().getNextId(IdentityType.ROLE));
                guard.setHostId(role.getRoleId());
            }
        }
        // 所有宠物
        HashMap<Integer, Integer> oldpetId_newpetId = new HashMap<>();
        {
            PetBox petBox = role.getPetBox();
            Map<Integer, Pet> allPets = new HashMap<>(petBox.getAllPets());
            petBox.getAllPets().clear();

            for (Map.Entry<Integer, Pet> entry : allPets.entrySet()) {
                entry.getValue().setId(SpringUtils.getIdentityService().getNextId(IdentityType.ROLE));
                oldpetId_newpetId.put(entry.getKey(), entry.getValue().getId());
                entry.getValue().setHostId(role.getRoleId());
                entry.getValue().setHostName(role.getName());
                petBox.getAllPets().put(entry.getValue().getId(), entry.getValue());
            }
            Integer integer = oldpetId_newpetId.get(petBox.getFightPetId());
            petBox.setFightPetId(integer == null ? 0 : integer);
            integer = oldpetId_newpetId.get(petBox.getSupplyPetId());
            petBox.setSupplyPetId(integer == null ? 0 : integer);
            integer = oldpetId_newpetId.get(role.getMount());
            role.setMount(integer == null ? 0 : integer);
            // 宠物仓库
            PetStore petStore = petBox.getPetStore();
            HashMap<Short, Integer> petInfo = new HashMap<>(petStore.getPetInfo());
            for (Map.Entry<Short, Integer> entry : petInfo.entrySet()) {
                integer = oldpetId_newpetId.get(entry.getValue());
                petStore.getPetInfo().put(entry.getKey(), integer);
            }
            // 宠物天书
            Map<Integer, PetBook> books = new HashMap<>(petBox.getBooks());
            petBox.getBooks().clear();
            for (Map.Entry<Integer, PetBook> entry : books.entrySet()) {
                entry.getValue().setId(SpringUtils.getBean(BookService.class).getId());
                integer = oldpetId_newpetId.get(entry.getValue().getPetId());
                entry.getValue().setPetId(integer == null ? 0 : integer);
                integer = oldequipId_newequipId.get(entry.getValue().getRoleEquipId());
                entry.getValue().setRoleEquipId(integer == null ? 0 : integer);
                petBox.getBooks().put(entry.getValue().getId(), entry.getValue());
            }
        }
        // 好友
//        {
//            FriendBox friendBox = role.getFriendBox();
//            ArrayList<Friend> friends = new ArrayList<>(friendBox.getFriends());
//            for (Friend friend : friends) {
//                if (friend.getGid().equals("")) {
//                    continue;
//                }
//                Long ll = oldUid_newUid.get(Long.parseLong(friend.getGid()));
//                if (ll != null) {
//                    friend.setGid(ll.longValue() + "");
//                } else {
//                    logger.error("好友数据找不到=={}", Json.toJson(friend, JsonFormat.compact()));
//                }
//            }
//        }
        // 技能
        {
            SkillBox skillBox = role.getSkillBox();
            for (Map.Entry<Integer, RoleSkill> entry : skillBox.getSkills().entrySet()) {
                entry.getValue().setRoleId(role.getRoleId());
                Integer integer = oldpetId_newpetId.get(entry.getValue().getRoleId());
                if (integer != null) {
                    entry.getValue().setRoleId(integer);
                }
            }
        }
        role.doBeforeSave();
        role.save();
    }

//    /**
//     * 查询玩家信息
//     */
//    @RequestMapping(method = RequestMethod.GET, path = "simplePlayer")
//    @ResponseBody
//    public Object querySimplePlayer(@RequestParam("username") String username) {
//        Account account = dao.fetch(Account.class, Cnd.where("username","=",username));
//        HashMap result = new HashMap();
//        if (account == null){
//            result.put("msg","账号不存在");
//            return result;
//        }
//        List<Role> roleList = dao.query(Role.class,Cnd.where("sid","=",account.getId()));
//        if (roleList == null || roleList.size()<=0){
//            result.put("msg","没有创建角色");
//            return result;
//        }
//        ArrayList arrayList = new ArrayList();
//        for (Role role:roleList){
//            HashMap hashMap = new HashMap();
//            hashMap.put("name",role.getName());
//            hashMap.put("roleId",role.getRoleId());
//            hashMap.put("uid",role.getUid());
//            hashMap.put("totalCharge",role.getTotalCharge());
//            hashMap.put("level",role.getLevel());
//
//            hashMap.put("money",role.getMoney());
//            hashMap.put("party",role.getPartyName() == null?"":role.getPartyName());
//            hashMap.put("siver",role.getSiver());
//
//            hashMap.put("taoPoint",role.getTao());
//            hashMap.put("storeMoney",role.getStoreMoney());
//            hashMap.put("banTrade",role.isBanTrade());
//            hashMap.put("stallGold",role.getStallCash());
//            hashMap.put("stallGold",role.getStallGold());
//            arrayList.add(hashMap);
//        }
//        HashMap hashMap = new HashMap();
//        hashMap.put("username",account.getUsername());
//        hashMap.put("id",account.getId());
//        hashMap.put("channelCode",account.getChannelCode());
//        hashMap.put("gold",account.getGold());
//        hashMap.put("privilege",account.getPrivilege());
//        result.put("account",hashMap);
//        result.put("list",arrayList);
//        return result;
//    }


//    @RequestMapping(method = RequestMethod.GET, path = "name")
//    @ResponseBody
//    public Object name(@RequestParam("roleId") long roleId,@RequestParam("name") String name) {
//        Role temp = dao.fetch(Role.class,Cnd.where("roleId","=",roleId));
//        HashMap result = new HashMap();
//        if (temp == null){
//            result.put("msg","角色不存在");
//            return result;
//        }
//        List<PlayerProfile> list = playerService.getPlayersBy(temp.getSid());
//        for (PlayerProfile playerProfile:list){
//            if (temp.getRoleId() == playerProfile.getRoleId()){
//                playerProfile.setName(name);
//                break;
//            }
//        }
//        Role role = playerService.getPlayerBy(temp.getUid());
//        role.setName(name);
//        role.save();
//        result.put("msg","修改角色名称成功");
//        return result;
//    }



//    /**
//     * 重载
//     */
//    @RequestMapping(method = RequestMethod.POST, path = "/reloadConfig")
//    public HttpResult reloadData(@RequestParam("tableName") String tableName) {
//        if ("all".equalsIgnoreCase(tableName)) {
//            myApplicationRunner.initTotal();
//            return HttpResult.valueOfOk("重载所有表格");
//        } else {
//            String returnObj = ProductDataPool.INSTANCE.reload(tableName);
//            return HttpResult.valueOfOk(returnObj);
//        }
//    }

//    /**
//     * 关服
//     */
//    @RequestMapping(method = RequestMethod.POST, path = "/closeServer")
//    public HttpResult stopServer() {
//        SchedulerManager.getInstance().schedule(() -> {
//            Map<Long, IoSession> map = gameServer.getAcceptor().getManagedSessions();
//            for (Map.Entry<Long, IoSession> entry : map.entrySet()) {
//                MessagePusher.pushMessage(entry.getValue(), new RespServerReboot());
//                closeSession(entry.getValue());
//            }
//            Runtime.getRuntime().exit(0);
//        }, 5 * TimeUtil.ONE_SECOND);
//
//        return HttpResult.valueOfOk("5秒后开始关服");
//    }

//    /**
//     * 清除黑名单
//     */
//    @RequestMapping(method = RequestMethod.POST, path = "/cleanBan")
//    public HttpResult cleanBan(@RequestParam(value = "ip", required = false, defaultValue = "all") String ip) {
//        if ("all".equals(ip)) {
//            ModuleCounterFilter.G_BAN_IP.clear();
//            return HttpResult.valueOfOk("清除全部黑名单IP");
//        } else {
//            ModuleCounterFilter.G_BAN_IP.remove(ip);
//            return HttpResult.valueOfOk("清除"+ ip + "黑名单IP， 当前黑名单个数:"
//                    + ModuleCounterFilter.G_BAN_IP.size());
//        }
//
//
//    }

//    public void closeSession(IoSession session) {
//        if (session == null) {
//            return;
//        }
//        Role role = SessionUtils.getRoleBySession(session);
//        String name = role != null ? role.getName() : "";
//        Logger logger = LoggerFunction.MONOIOR.getLogger();
//        if (session.isConnected() && !session.isClosing()) {
//            CloseFuture future = session.closeNow();
//            future.addListener(new IoFutureListener<IoFuture>() {
//                @Override
//                public void operationComplete(IoFuture future) {
//                    logger.error("session[{}] closed complete,player[{}]", session.getId(), name);
//                }
//            });
//        }
//
//        if (role != null) {
//            SpringUtils.getRoleService().removeOnline(role);
//            SpringUtils.getRoleService().addOffline(role);
//        }
//
//    }

//    /**
//     * 执行groovy脚本
//     */
//    @RequestMapping(method = RequestMethod.POST, path = "/runScript")
//    public HttpResult runScript(@RequestParam("script") String script) {
//        String returnObj = SpringUtils.getBean(GameMonitor.class).execGroovyScript(script);
//        return HttpResult.valueOfOk(returnObj);
//    }


}
